﻿using JV.Com.Business;
using JV.Com.Internals;
using JV.Com.Model;
using JV.Com.ViewModels.Wrapper;
using Microsoft.Practices.Prism.StoreApps;
using Microsoft.Practices.Prism.StoreApps.Interfaces;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Documents;

namespace JV.Com.ViewModels
{
    public sealed class NewsListPageViewModel : PageBaseViewModel
    {
        public NewsListPageViewModel(INavigationService navigationService)
            : base(navigationService)
        {
        }

        public override void OnNavigatedTo(object navigationParameter, Windows.UI.Xaml.Navigation.NavigationMode navigationMode, Dictionary<string, object> viewModelState)
        {
            base.OnNavigatedTo(navigationParameter, navigationMode, viewModelState);
            if (navigationMode == Windows.UI.Xaml.Navigation.NavigationMode.New)
            {
                SelectedNewsId = (int)navigationParameter;
            }

            m_news = new NewsItemDetailCollection(this, SelectedNewsId);
            OnPropertyChanged("News");
        }

        public override string PageTitle
        {
            get { return "Actualités"; }
        }

        private NewsItemDetailCollection m_news;
        public NewsItemDetailCollection News
        {
            get { return m_news; }
            set { SetProperty<NewsItemDetailCollection>(ref m_news, value); }
        }

        private int m_selectedNewsIndex;
        public int SelectedNewsIndex
        {
            get { return m_selectedNewsIndex; }
            set
            {
                SetProperty<int>(ref m_selectedNewsIndex, value);
                SelectedNewsId = m_news[m_selectedNewsIndex].Id;
            }
        }

        private int m_selectedNewsId;
        [RestorableState]
        public int SelectedNewsId
        {
            get { return m_selectedNewsId; }
            set { SetProperty<int>(ref m_selectedNewsId, value); }
        }

        public async Task SelectNewsByIdAsync(int newsId)
        {
            var dispatcher = Window.Current.Dispatcher;
            SelectedNewsId = newsId;
           
            for(int i = 0; i < m_news.Count; i++)
            {
                var news = m_news[i];
                if (news.Id == newsId)
                {
                    SelectedNewsIndex = i;
                    await news.LoadContentAsync();
                    return;
                }
            }

            var newNews = new News() { Id = newsId };
            var wrapper = new NewsWrapper(this, newNews);
            m_news.Add(wrapper);
            SelectedNewsIndex = m_news.Count - 1;
        }
    }
}
